package api

import (
	"encoding/json"
	"gin-gorm-learn/dao"
	"github.com/gin-gonic/gin"
	"net/http"
)

func SaveStudent(ctx *gin.Context) {
	student := &dao.Student{
		Name: "GIN",
		Sex:  1,
		Age:  45,
	}
	dao.SaveStudent(student)
	ctx.JSON(http.StatusOK, student)
}

func GetStudentById(ctx *gin.Context) {
	student := dao.GetStudentById(5)
	ctx.JSON(http.StatusOK, student)
}

func GetAllStudent(ctx *gin.Context) {
	students := dao.GetAllStudent()
	ctx.JSON(http.StatusOK, students)
}

func UpdateStudent(ctx *gin.Context) {
	dao.UpdateStudent(5)
	student := dao.GetStudentById(5)
	ctx.JSON(http.StatusOK, student)
}

func DeleteStudent(ctx *gin.Context) {
	dao.DeleteStudent(5)
	student := dao.GetStudentById(5)
	ctx.JSON(http.StatusOK, student)
}

func GetStudentSql(ctx *gin.Context) {
	student := dao.GetStudentSql(3)
	ctx.JSON(http.StatusOK, student)
}

// 获取请求url ? 后的参数（url:8080/add?name=kelvin）
func GetUrlParam(ctx *gin.Context) {
	name := ctx.Query("name")
	defaultName := ctx.DefaultQuery("name", "defaultName...")
	ctx.JSON(http.StatusOK, gin.H{
		"name":        name,
		"defaultName": defaultName,
	})
}

// 获取请求表单的参数
func GetFormParam(ctx *gin.Context) {
	formName := ctx.PostForm("name")
	defaultPostFormName := ctx.DefaultPostForm("name", "default name form ~~~")
	ctx.JSON(http.StatusOK, gin.H{
		"formName":            formName,
		"defaultPostFormName": defaultPostFormName,
	})
}

// 获取请求Json参数体
func GetJson(ctx *gin.Context) {
	data, err := ctx.GetRawData()
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"msg": "获取json数据异常",
		})
	}
	var m map[string]interface{}
	// 反序列化
	_ = json.Unmarshal(data, &m)
	ctx.JSON(http.StatusOK, gin.H{
		"json": &m,
	})
}

// 获取请求url中的路径参数（url:8080/add/:name/:age）
func GetUrlPathParam(ctx *gin.Context) {
	name := ctx.Param("name")
	age := ctx.Param("age")
	ctx.JSON(http.StatusOK, gin.H{
		"name": name,
		"age":  age,
	})
}
